//
// Created by cmo on 2022/5/14.
//

#include "util.h"

// public native int getBasicData();

extern "C"
JNIEXPORT jint JNICALL
Java_com_crazymo_jni_ProcessJavaDataHelper_getBasicData(JNIEnv *env, jobject thiz) {
    return 8888888;
}


extern "C"
JNIEXPORT jstring JNICALL
Java_com_crazymo_jni_ProcessJavaDataHelper_getStringData(JNIEnv *env, jobject thiz) {
    char* tmpstr = "从JNI发送到Java的字符串";
    jstring rtstr = env->NewStringUTF(tmpstr);
    return rtstr;
}
extern "C"
JNIEXPORT jintArray JNICALL
Java_com_crazymo_jni_ProcessJavaDataHelper_getIntArrayData(JNIEnv *env, jobject thiz,jint len) {
    //主要调用 set<Type>ArrayRegion 来填充数据，其他数据类型类似操作
    jintArray array = NULL;
    if (len > 0) {
        array = env->NewIntArray(len);
        jint buf[len];
        for (int i = 0; i < len; ++i) {
            buf[i] = i * 2;
        }
        // 使用 setIntArrayRegion 来赋值
        env->SetIntArrayRegion(array, 0, len, buf);
        return array;
    }
    return array;
}
extern "C"
JNIEXPORT jobject JNICALL
Java_com_crazymo_jni_ProcessJavaDataHelper_getListData(JNIEnv *env, jobject thiz, jint size) {
    jclass listClz=env->FindClass("java/util/ArrayList");
    jmethodID constructId=env->GetMethodID(listClz,"<init>","()V");
    jmethodID addId=env->GetMethodID(listClz,"add","(Ljava/lang/Object;)Z");
    jobject listObj=env->NewObject(listClz,constructId);
    jstring newAddr=env->NewStringUTF("在Native层创建Java List对象");
    for (int i = 0; i < size; ++i) {
        ///const char *c_newAddr = env->GetStringUTFChars(newAddr, 0);
        ///env->CallBooleanMethod(list_obj,add_method,c_newAddr);
        env->CallBooleanMethod(listObj,addId,newAddr);
    }
    //env->ReleaseStringChars(newAddr,0); TODO 为什么调用这个方法会异常
    env->DeleteLocalRef(listClz);
    return listObj;
}
extern "C"
JNIEXPORT jobject JNICALL
Java_com_crazymo_jni_ProcessJavaDataHelper_getMapData(JNIEnv *env, jobject thiz, jint size) {
    jclass mapClz=env->FindClass("java/util/HashMap");
    jmethodID constructId=env->GetMethodID(mapClz,"<init>","()V");
    jmethodID putId=env->GetMethodID(mapClz,"put","(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
    jobject map_obj=env->NewObject(mapClz,constructId);
    jstring key = env->NewStringUTF("CrazyMo_");
    jstring value = env->NewStringUTF("在C++创建Java Map对象");
    env->CallObjectMethod(map_obj,putId,key,value);
    return map_obj;
}